package com.lagou.edu.support;

import com.lagou.edu.connector.Endpoint;
import com.lagou.edu.connector.adapter.Adapter;
import com.lagou.edu.container.Engine;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * service，关联多个连接器和容器
 * <p>
 * 容器中包含多个context，这里省去了容器这一层，直接关联了多个连接器和多个context
 *
 * @author liangzj
 * @date 2021/4/6 22:50
 */
public class Service {

    // 连接器列表
    private List<Endpoint> endpoints;

    private Engine engine;

    // 默认线程数
    private static final int THREAD_SIZE = 5;

    /**
     * 连接器启动线程池，启动连接器也需要线程池，因为连接器启动后会阻塞线程，等待请求，
     * 如果只有一个线程，那么只有第一个连接器会启动，其余连接器会被阻塞
     */
    private ThreadPoolExecutor DEFAULT_CONNECTOR_EXECUTOR = new ThreadPoolExecutor(
            THREAD_SIZE,
            THREAD_SIZE,
            100L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(50),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public Service(List<Endpoint> endpoints, Engine engine) {
        this.endpoints = endpoints;
        this.engine = engine;
    }

    public void start() {
        for (Endpoint endpoint : endpoints) {
            DEFAULT_CONNECTOR_EXECUTOR.execute(() -> {
                try {
                    // 创建连接器
                    endpoint.create();
                    // 创建请求适配器
                    Adapter adapter = new Adapter(endpoint, engine);
                    // 通过适配器处理请求
                    adapter.handleRequest();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }


}
